<?php
namespace Controller\Skusystem\Api;

use Library\Log;
use Model\Skusystem\SkuModel;


/**
 * SkuController
 * @author los_gsy
 * TODO: 从yks skusystem迁移过来，需要再根据本系统的环境进行修改。
 */
class SkuController {
	/**
	 * test
	 */
	public function action_test() {
		echo __METHOD__;
		echo '<br />';
	}


	/**
	 * tmp
	 */
	public function action_tmp() {
		//$url = 'http://www.mpf.lab/Cron/Sku/test';
		$url = 'http://me.skusystem.yks.com/sample/test';
		$header = array('Accept' => 'application/json');
		$option = array('auth' => array('user', 'pass'));
		$request = Requests::get($url, $header);	//, $option);

		// int(200)
		var_dump($request->status_code);
		echo '<br />';

		// string(31) "application/json; charset=utf-8"
		var_dump($request->headers['content-type']);
		echo '<br />';

		// string(26891) "[...]"
		var_dump($request->body);
		echo '<br />';

// 		$result = curl_get($url, $header);
// 		var_dump($result);
	}


	/**
	 * 获取最近更新的sku列表
	 * 获取方式：分页，每页大小上限1000条记录
	 * @return array	sku总数，每页sku列表
	 */
	public function action_getSkuList() {
		//定义变量
		$conf = include APPPATH . 'config/conf.php';
		$ret = $conf['status'][200];
		$httpBasicAuth = $conf['skusystem']['http_basic_auth'];
		$username = $httpBasicAuth['username'];
		$passwd = $httpBasicAuth['passwd'];
		$begin_update_at = date('Y-m-d', strtotime('-1 day'));

		//验证权限，通过http basic authentication: $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW']
		if (!isset($_SERVER['PHP_AUTH_USER'])) {
			header('WWW-Authenticate: Basic realm="Enter your username and password"');
			header('HTTP/1.0 401 Unauthorized');
			//Text to send if user hits Cancel button
			$ret = $conf['status'][410101];
			Log::warning(__METHOD__ . ' ' . var_export($ret, true));
			exit(json_encode($ret));
		}
		if ($username != $_SERVER['PHP_AUTH_USER'] || $passwd != $_SERVER['PHP_AUTH_PW']) {
			$ret = $conf['status'][410102];
			Log::warning(__METHOD__ . ' ' . var_export($ret, true));
			exit(json_encode($ret));
		}

		//获取参数
		$updatedAt = I('updatedAt', $begin_update_at);
		$page = I('page', 1, array('trim', 'intval'));
		$pagesize = I('pagesize', 20, array('trim', 'intval'));
// 		Log::debug(__METHOD__ . ' $_GET: ' . var_export($_GET, true));
// 		Log::debug(__METHOD__ . ' $_REQUEST: ' . var_export($_REQUEST, true));
// 		Log::debug(__METHOD__ . ' $_SERVER: ' . var_export($_SERVER, true));
		Log::debug(__METHOD__ . ' page: ' . $page);
		Log::debug(__METHOD__ . ' pagesize: ' . $pagesize);

		//查询最近更新的sku列表
		$skuResult = SkuService::getSkuListByUpdatedAt($updatedAt, $page, $pagesize);

		//Success
		$ret['skuResult'] = $skuResult;
		exit(json_encode($ret));
	}


}
